<template>
  <div :class="['my-page', currentTheme]">
    <header class="top-bar">
      <h2>个人主页</h2>
      <div class="top-bar-right">
        <select v-model="currentTheme" class="theme-selector" title="切换主题">
          <option value="theme-pink">粉色主题</option>
          <option value="theme-blue">蓝色主题</option>
          <option value="theme-green">绿色主题</option>
        </select>
        <button class="back-button" @click="goBack">返回推荐页</button>
      </div>
    </header>

    <section class="profile-section">
      <img class="avatar" :src="user.avatar" alt="头像" />
      <div class="user-info">
        <h3 class="username">{{ user.name }}</h3>
        <p class="bio">{{ user.bio }}</p>
      </div>
    </section>

    <section class="posts-section">
      <h3>我的帖子</h3>
      <div class="posts-grid">
        <div 
          v-for="post in posts" 
          :key="post.postId" 
          class="post-item"
        >
          <img :src="post.image" alt="帖子图片" class="post-image" @click="goToPost(post.postId)" />
          <p class="post-desc">{{ post.description }}</p>
          <div class="post-actions">
<button @click="openEditModal(post)">编辑</button>
            <button @click="deletePost(post.postId)">删除</button>
          </div>
        </div>

        <div v-if="posts.length === 0" class="no-posts">暂无帖子</div>
      </div>
    </section>

    <div class="pagination-container">
      <button :disabled="!hasPrevPage" @click="prevPage">上一页</button>
      <span class="page-info">第 {{ currentPage }} 页</span>
      <button :disabled="!hasNextPage" @click="nextPage">下一页</button>
    </div>




<!-- 悬浮窗模态框 -->
<div class="modal-mask" v-if="visible">
  <div class="modal-container">
    <h3>编辑帖子</h3>
    <label>标题：</label>
    <input v-model="editTitle" type="text" class="modal-input"/>

    <label>内容：</label>
    <textarea v-model="editContent" rows="4" class="modal-textarea"></textarea>

    <div class="modal-actions">
      <button class="save-btn" @click="handleSave">保存</button>
      <button class="cancel-btn" @click="close">取消</button>
    </div>
  </div>
</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import api from "@/utils/request";

const currentTheme = ref("theme-pink");
const router = useRouter(); 

const currentPage = ref(1);
const pageSize = 4;
const hasNextPage = ref(true); // 判断是否还有更多
const hasPrevPage = computed(() => currentPage.value > 1);

const posts = ref<any[]>([]); // 保存从后端获取的帖子
const props = defineProps<{
  visible: boolean;
  post: any;
}>();

const emit = defineEmits(["close", "refresh"]);

const editTitle = ref("");
const editContent = ref("");
const user = ref({
  avatar: "https://i.pravatar.cc/150?img=12",
  name: "",
  bio: "这个人很懒，什么也没写。",
  id:null,
});//获取用户个人信息

function goToPost(postId: number) {
  // ToDo: 跳转帖子详情页

  router.push(`/post/${postId}`);

  alert(`跳转到帖子ID: ${postId}`);
}

function goBack() {
  router.push("/recommend");
}



const visible = ref(false);

const editingPostId = ref<number | null>(null); // 当前正在编辑的 postId

function openEditModal(post: any) {
  editingPostId.value = post.postId;
  editTitle.value = post.description; // 用 description 存标题
  editContent.value = post.description; // 如果 content 和 title 一样，用这个，否则从 post.content
  visible.value = true;
}

function close() {
  visible.value = false;
  editingPostId.value = null;
  editTitle.value = "";
  editContent.value = "";
}

async function handleSave() {
  if (!editingPostId.value) return;
  try {
    const res = await api.put(`/user/my/post`, {
  data: {
       title: editTitle.value,
      content: editContent.value,
      id:editingPostId.value
    }

      },);
    if (res.code === 200) {
      alert("修改成功");
      fetchPosts(); // 重新加载
      close();
    } else {
      alert(`修改失败：${res.message || "未知错误"}`);
    }
  } catch (err) {
    console.error("修改失败", err);
    alert("请求失败");
  }
}

function editPost(postId: number) {
  // 假设你有 /edit/:postId 页面
  router.push(`/edit/${postId}`);
}

async function deletePost(postId: number) {
  if (!confirm("确定要删除该帖子吗？")) return;

  try {
    const res = await api.delete(`/user/my/post`,{
       data: {
    id: postId
  },
  headers: {
    "Content-Type": "application/json"
  }
    },);
    if (res.code === 200) {
      alert("删除成功");
      fetchPosts(); // 重新加载帖子
    } else {
      alert(`删除失败：${res.message || "未知错误"}`);
    }
  } catch (err) {
    console.error("删除失败", err);
    alert("删除失败，请稍后再试");
  }
}

const userId = Number(localStorage.getItem("userId") || 0);

async function fetchUserInfo() {
  try {
    const res = await api.get(`/auth/user/getByUserId`);
    if (res.code === 200) {
      const data = res;
      user.value.name = data.username;
      user.value.id = data.user_id;
    } else {
      alert(`获取用户信息失败：${res}`);
    }
  } catch (err) {
    console.error("获取用户信息失败：", err);
    alert("请求用户信息失败");
  }
}

async function fetchPosts() {
  try {
    const res = await api.get("/user/my/post", {
      params: {
        pageNo: currentPage.value,
        pageSize,
      },
    });

    if (res.code === 200) {
      const data = res.data;
      posts.value = data.map((item: any) => ({
        id: item.videoId,
        // image: item.coverUrl,
        image: `data:image/jpeg;base64,${item.image_base64}`,
        description: item.title,
        postId: item.id,
      }));

      // 如果返回数量 < pageSize，说明是最后一页
      hasNextPage.value = data.length === pageSize;
    } else {
      alert(`获取帖子失败：${res}`);
    }
  } catch (err) {
    console.error("请求失败", err);
    alert("请求失败，请稍后再试");
  }
}


function nextPage() {
  if (hasNextPage.value) {
    currentPage.value++;
    fetchPosts();
  }
}

function prevPage() {
  if (hasPrevPage.value) {
    currentPage.value--;
    fetchPosts();
  }
}



// 页面加载时获取数据
onMounted(() => {
  fetchPosts();
  fetchUserInfo();
});

</script>

<style src="./MyPage.css"></style>
